const request = require('request-promise');
const mysql = require('mysql');
const mysqlConfig = require('./mysqlconfig.js');

// 获取所有可转债编码
function wrapGetAllCodePromise(connection) {
  return new Promise((res, rej) => {
    connection.query('SELECT code from convertible_bond_hook', function(error, results, fields) {
      if (error) {
        rej(error)
      }
      res(results)
    })
  })
}

// 获取可转债价格
async function wrapGetAllPricePromise(allCode) {
  const codes = allCode.map(({code}) => code.toLowerCase()).join(',');
  let prices = await request({
    url: `http://hq.sinajs.cn/list=${codes}`,
    timeout: 10000
  });
  prices = prices.replace(/\n/g, '');

  return prices.split(';').reduce((total, priceItem) => {
    const [codeStr, priceStr] = priceItem.split('=');
    if (!codeStr || !priceStr) return total;
    const code = codeStr.replace('var hq_str_', '');
    const price = priceStr.split(',')[3];
    if (!price || !code) return total;
    total.push([Number(price), code]);
    return total;
  }, []);
}

// 将价格写入数据库
function wrapWritePriceIntoDB(connection, codeAndPrices) {
  const model_sql = 'UPDATE convertible_bond_hook SET price=? WHERE code=?;';
  return new Promise((res, rej) => {
    let sqls = codeAndPrices.map((item) => {
      return mysql.format(model_sql, item);
    }).join('');
    connection.query(sqls, function(error, results, fields) {
      if (error) {
        rej(error)
      }
      res(results)
    })
  })
}

exports.main_handler = async (event, context, callback) => {
  let res = null;
  let connection = null;
  try {
    connection = mysql.createConnection({
      ...mysqlConfig,
      charset : 'utf8mb4',
      multipleStatements: true
    });
    connection.connect();
    const allCode = await wrapGetAllCodePromise(connection);
    const allCodeAndPrice = await wrapGetAllPricePromise(allCode);
    const result = await wrapWritePriceIntoDB(connection, allCodeAndPrice);
    res = {allCodeAndPrice, result};
  } catch (error) {
    console.log('error', error);
    res = error;
  } finally {
    connection && connection.end();
  }
  return res;
}
